var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//导入api设置
// var accountRouter = require('./routes/api/account');
var auhtApiRouter = require('./routes/api/auth');
var userApiRouter = require('./routes/api/user');
var salaryApiRouter = require('./routes/api/salary');
var departmentApiRouter = require('./routes/api/department');


//导入 express-session 
const session = require("express-session"); // 会话中间件
const MongoStore = require('connect-mongo'); // 会话存储中间件
//导入配置项
const { DBHOST, DBPORT, DBNAME } = require('./config/config');

var app = express();
//设置 session 的中间件

app.use(session({
  name: 'sid',   //设置cookie的name，默认值是：connect.sid
  secret: 'atguigu', //参与加密的字符串（又称签名）  加盐
  saveUninitialized: false, //是否为每次请求都设置一个cookie用来存储session的id
  resave: true,  //是否在每次请求时重新保存session  20 分钟    4:00  4:20
  store: MongoStore.create({
    mongoUrl: `mongodb://${DBHOST}:${DBPORT}/${DBNAME}` //数据库的连接配置
  }),
  cookie: {
    httpOnly: true, // 开启后前端无法通过 JS 操作
    maxAge: 1000 * 60 * 60 * 24 * 7 // 这一条 是控制 sessionID 的过期时间的！！！
  },
}))
// 跨域中间件放在会话中间件之后
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // 允许前端的地址
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Headers', '*');
  res.header('Access-Control-Allow-Credentials', true);
  next();
});

app.use(logger('dev')); // 日志中间件
app.use(express.json()); // 解析 JSON 请求体
app.use(express.urlencoded({ extended: false })); // 解析 URL-encoded 请求体
app.use(cookieParser()); // 解析 Cookie
app.use(express.static(path.join(__dirname, 'public'))); // 配置静态文件目录

// 配置路由
// app.use('/api', accountRouter);
app.use('/api', auhtApiRouter);
app.use('/api', userApiRouter);
app.use('/api', salaryApiRouter);
app.use('/api', departmentApiRouter);

// 配置静态文件目录
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.json({
    code: '2003', //2001 服务器问题
    msg: '未找到该接口',
    data: null,
    status: false,
})
});



// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
